package aes.gui;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;

import aes.general.FileSend;
import aes.general.GuiControlBeta;
import aes.general.StudentControl;

/**
 * The Class StudentMakeExamManualSubmitPane.
 * This panel is indicating the student that is making the manual exam 
 *  of the time left to submit the exam. When the time runs up the
 *   student won't be able to submit anymore.   
 */
public class StudentMakeExamManualSubmitPane extends JPanel {

    
	private static final long serialVersionUID = 1L;
	JLabel lblTimeLeft;
	private JLabel label;
	private JLabel label_1;
	private JLabel lblSubmitExam;
	private JLabel lblNewLabel;
	private JLabel lblNewLabel_1;
	private JButton btnSubmit;
	private JSeparator separator;
	private static JPanel cp = null;
	
	private String examDurationOriginal = null;
	private static Integer timeleft = null;
	private static String examid;
	private static Timer timer = null;
	private static Timer timer2;
	private static boolean timeAddedFlag = false;
	private static boolean examlocked = false;
	private static long timeToAdd;


		
	/**
	 * Create the panel.
	 * 
	 * @param contentPane
	 *            the content pane
	 * @param examDurOrig
	 *            the exam duration original
	 * @param examIdm
	 *            the exam id
	 */
	public StudentMakeExamManualSubmitPane(JPanel contentPane , String examDurOrig,  String examIdm) {
		this.timeAddedFlag = false;
		this.examlocked = false;
		cp=contentPane;
		examDurationOriginal = examDurOrig;
		timeleft = Integer.parseInt(examDurOrig);   
		examid = examIdm;
		setLayout(null);
		
		lblSubmitExam = new JLabel("Examinating");
		lblSubmitExam.setFont(new Font("Tempus Sans ITC", Font.BOLD, 21));
		lblSubmitExam.setBounds(235, 11, 169, 29);
		add(lblSubmitExam);
		
		separator = new JSeparator();
		separator.setBounds(18, 55, 603, 2);
		add(separator);
		
		btnSubmit = new JButton("Submit");
		btnSubmit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				FileDialog fileDialog = new FileDialog(new Frame(), "Open", FileDialog.LOAD);
				fileDialog.setVisible(true);
				
			    FileSend  msg= new FileSend(fileDialog.getFile());
			    msg.setExamID(examid);
			    msg.setStudentId(GuiControlBeta.userid);
				  
			if(fileDialog.getFile()==null) return; //user clicked cancel
				
				  String LocalfilePath=fileDialog.getDirectory()+fileDialog.getFile();
					
				  try{
					      File newFile = new File (LocalfilePath);
					      		      
					      byte [] mybytearray  = new byte [(int)newFile.length()];
					      FileInputStream fis = new FileInputStream(newFile);
					      BufferedInputStream bis = new BufferedInputStream(fis);			  
					      
					      msg.initArray(mybytearray.length);
					      msg.setSize(mybytearray.length);
					      
					      bis.read(msg.getMybytearray(),0,mybytearray.length);
					       
					      StudentControl.SendManualExamFile(msg); 
						  System.out.println( msg.getSize() );
						  System.out.println( msg.getFileName() );
					    }
					catch (Exception e) {
						System.out.println("Error send (Files)msg) to Server");
					}   
				  StudentControl.DeleteActivationCode(examid); 
				  JOptionPane.showMessageDialog(null, "Exam sended,Good Luck", "",
							JOptionPane.INFORMATION_MESSAGE);
				  timer.cancel();
					CardLayout cl = (CardLayout) (cp.getLayout());
					cl.show(cp, "MainPanel");
			}
		});
		btnSubmit.setBounds(273, 327, 145, 23);
		add(btnSubmit);
		
		label = new JLabel("Time Left : ");
		label.setBackground(Color.BLACK);
		label.setFont(new Font("Tempus Sans ITC", Font.BOLD, 21));
		label.setBounds(44, 83, 169, 29);
		add(label);
		
		lblTimeLeft = new JLabel(examDurOrig);
		lblTimeLeft.setFont(new Font("Arial", Font.BOLD, 25));
		lblTimeLeft.setForeground(Color.RED);
		lblTimeLeft.setBackground(Color.RED);
		lblTimeLeft.setBounds(161, 73, 65, 45);
		add(lblTimeLeft);
		
		label_1 = new JLabel("Minutes");
		label_1.setFont(new Font("Tempus Sans ITC", Font.BOLD, 21));
		label_1.setBackground(Color.BLACK);
		label_1.setBounds(226, 83, 169, 29);
		add(label_1);
		
		lblNewLabel = new JLabel("Click \"Submit\" button to upload your Exam file with selected answers ");
		lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 13));
		lblNewLabel.setBounds(96, 220, 477, 14);
		add(lblNewLabel);
		
		lblNewLabel_1 = new JLabel("When the time hits 0 you won't be able to upload the exam!\r\n");
		lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 13));
		lblNewLabel_1.setBounds(121, 268, 422, 14);
		add(lblNewLabel_1);
			
		timerfunction();
	}
	

	/**
	 * Add time function.
	 * 
	 * @param time
	 *            the time in minutes to add to exam duration
	 */
	public static void addtimefunc(String time)
	{
		timeAddedFlag=true;
		timeToAdd=Integer.valueOf(time);
		timeleft= (int) (timeToAdd+timeleft);
		 timer2 = new Timer();

		timer2.schedule(  new TimerTask() {
			  @Override
			  public void run() {
				  			JOptionPane.showMessageDialog(null, "Sorry.Time ended", "",
							JOptionPane.INFORMATION_MESSAGE);			  			
						     StudentControl.DeleteActivationCode(examid); 				  
							CardLayout cl = (CardLayout) (cp.getLayout());
							cl.show(cp, "MainPanel");
							cancel();  	  
			  }
			}
		, TimeUnit.MINUTES.toMillis(timeleft));
	
	}
	
	
	
	private void timerfunction() {
		
		
	timer = new Timer();
	
	timer.schedule(  new TimerTask() {
		  @Override
		  public void run() {
				if (timeAddedFlag==true) {cancel();return;}
				JOptionPane.showMessageDialog(null, "Sorry.Time ended", "",
						JOptionPane.INFORMATION_MESSAGE);
				
			  
			     StudentControl.DeleteActivationCode(examid); 
			  
				CardLayout cl = (CardLayout) (cp.getLayout());
				cl.show(cp, "MainPanel");
				timer.cancel();
			  
			  
		  }
		}
	, TimeUnit.MINUTES.toMillis(Integer.parseInt(examDurationOriginal)));

	
	timer.scheduleAtFixedRate(  new TimerTask() {
		  @Override
		  public void run() {
			  		
			  timeleft--;	  
			  lblTimeLeft.setText(String.valueOf(timeleft));
			  
		  }
		}
	,TimeUnit.MINUTES.toMillis(1),TimeUnit.MINUTES.toMillis(1));
	
	timer.scheduleAtFixedRate(  new TimerTask() {
		  @Override
		  public void run() {
			  		
			  	if (examlocked==true) 
			  	{
			  		
			  		StudentControl.DeleteActivationCode(examid); //delete activation code		  			
		  			CardLayout cl = (CardLayout) (cp.getLayout());
		  			cl.show(cp, "MainPanel");
			  		timer.cancel();
			  		if(timer2!=null )timer2.cancel();
			  		
			  	}
			  
		  }
		}
	,1000,1000);
	}


	/**
	 * Lock exam function.Changes flag for timer thread ,responsible for exam termination
	 * 
	 * @param string
	 *         
	 */
	public static void lockexamfunc(String string) {
		examlocked=true;		
	}
}
